package com.example.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.example.entity.Account;
import com.example.entity.Category;
import com.example.entity.Introduction;
import com.example.mapper.IntroductionMapper;
import com.example.mapper.UserMapper;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class IntroductionService {

    @Autowired
    private IntroductionMapper introductionMapper;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private UserMapper userMapper;

    public List<Introduction> selectAll() {
        return introductionMapper.selectAll(null);
    }


    public PageInfo<Introduction> selectPage(Integer pageNum, Integer pageSize, Introduction introduction) {
        // 查之前要先给他条件
        Account currentUser = TokenUtils.getCurrentUser();
        if ("USER".equals(currentUser.getRole())) {
            introduction.setUserId(currentUser.getId());
        }
        // 开启分页查询
        PageHelper.startPage(pageNum,pageSize);
        List<Introduction> list = introductionMapper.selectAll(introduction);
        for (Introduction dbIntroduction : list) {
            Integer categoryId = dbIntroduction.getCategoryId();
            Integer userId = dbIntroduction.getUserId();
            Account user = userMapper.selectById(userId.toString());
            Category category = categoryService.selectById(categoryId);
            System.out.println("category====>"+categoryId+category);
            if(ObjectUtil.isNotEmpty(category)){
                dbIntroduction.setCategoryName(category.getTitle());
            }
            if(ObjectUtil.isNotEmpty(user)){
                dbIntroduction.setUserName(user.getUsername());
            }

        }
        return PageInfo.of(list);
    }
    public void add(Introduction introduction){
        Account user = TokenUtils.getCurrentUser();
        introduction.setUserId(user.getId());
        introduction.setTime(DateUtil.now());
        introductionMapper.insert(introduction);
    }

    public void update(Introduction introduction) {
//        if(introductionMapper.selectByIntroductionname(introduction.getIntroductionname())!=0){
//            throw new CustomerException("账号重复");
//        }
        introductionMapper.updateById(introduction);
    }

    public void deleteById(Integer id) {
        introductionMapper.deleteById(id);
    }

//    public void deleteBatch(List<Introduction> list) {
//        for (Introduction introduction : list) {
//            this.deleteById(introduction.getId());
//        }
//    }

}